package org.example.dataStructure.linkedList;

/**
 * @author yuwl
 * @description 链表
 * @since 2024-07-12 15:09
 */
public class ListNodeDemo {

    public static void main(String[] args) {
        // 1.初始化链表 1->3->2->5->4
        ListNode n0 = new ListNode("1");
        ListNode n1 = new ListNode("3");
        ListNode n2 = new ListNode("2");
        ListNode n3 = new ListNode("5");
        ListNode n4 = new ListNode("4");
        // 构建节点之间的引用
        n0.next = n1;
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;

        // 2.插入节点
        ListNode p = new ListNode("p");
        insert(n0, p);

        // 3.删除节点
        remove(n0);

        // 4.访问节点
        ListNode accessNode = access(n0, 3);
        System.out.println("accessNode = " + accessNode.message);

        // 5.查找节点
        int index = find(n0, "4");
        System.out.println("index = " + index);
    }

    /**
     * 查找节点
     * @param head
     * @param target
     * @return
     */
    public static int find(ListNode head, String target) {
        int index = 0;
        while (head != null) {
            if (head.message.equals(target)) {
                return index;
            }
            head = head.next;
            index++;
        }
        return index;
    }

    /**
     * 返回链表中索引为 index 的节点
     * @param head
     * @param index
     * @return
     */
    public static ListNode access(ListNode head, int index) {
        for (int i = 0; i < index; i++) {
            if (head == null) {
                return null;
            }
            head = head.next;
        }
        return head;
    }

    /**
     * 删除链表的节点 n0 之后的首个节点
     * @param n0
     */
    public static void remove(ListNode n0) {
        if (n0.next == null) {
            return;
        }
        ListNode p = n0.next;
        ListNode n1 = p.next;
        n0.next = n1;
    }

    /**
     * 在链表节点 n0 之后插入节点 p
     * @param n0
     * @param p
     */
    public static void insert(ListNode n0, ListNode p) {
        ListNode n1 = n0.next;
        p.next = n1;
        n0.next = p;
    }
}
